package com.cn.wanxi.servlet.back.user;

import com.cn.wanxi.dto.UserDto;
import com.cn.wanxi.model.PageModel;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import net.sf.json.JSON;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/userFindAll")
public class UserFindAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        2.得到页面的值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String ageStart = req.getParameter("ageStart");
        String ageEnd = req.getParameter("ageEnd");

        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");


//        3.封装页面传递过来的值model
        PageModel pageModel = new PageModel();
        pageModel.setPageNum("".equals(pageNum) ? 1 : Integer.parseInt(pageNum));
        pageModel.setPageSize("".equals(pageSize) ? 10 : Integer.parseInt(pageSize));
        UserDto userDto = new UserDto();
        userDto.setUserModel(new UserModel());
        userDto.getUserModel().setUsername(username);
        userDto.getUserModel().setPassword(password);
        userDto.getUserModel().setSex("".equals(sex) ? 2 : Integer.parseInt(sex));
        userDto.setAgeStart("".equals(ageStart) ? 0 : Integer.parseInt(ageStart));
        userDto.setAgeEnd("".equals(ageEnd) ? 100 : Integer.parseInt(ageEnd));

//        排序，如果开始年龄大于结束年龄，需要交换值
        if (userDto.getAgeStart() > userDto.getAgeEnd()) {
            int temp = 0;
            temp = userDto.getAgeStart();
            userDto.setAgeStart(userDto.getAgeEnd());
            userDto.setAgeEnd(temp);
        }
//        4.调用服务逻辑层
        IUserService iUserService = new UserServiceImpl();
//        List<UserModel> list = iUserService.findAll(userDto, pageModel);
        ResultModel resultModel=iUserService.findAll(userDto, pageModel);
//        5.返回页面
        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);
//        req.getRequestDispatcher("/back/userFindAll.jsp").forward(req, resp);

    }
}
